/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fourbox;

import java.sql.*;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author hartono
 */
public class DBHelper {

    public static boolean login(String username, String password) {
        try {
            Connection mConn = null;
            Statement mStatement = null;
            try {
                Class.forName("com.mysql.jdbc.Driver");
                mConn = DriverManager.getConnection("jdbc:mysql://localhost/progin_4", "progin", "progin");
                mStatement = mConn.createStatement();

                String query = "SELECT * from `user` where `username` = '" + username + "'";
                System.out.println("Query : " + query);
                ResultSet results = mStatement.executeQuery(query);
                while (results.next()) {
                    String rPassword = results.getString("password");
                    System.out.println("rPass "+rPassword + " , "+ password);
                    if (rPassword.equals(password)) {
                        mStatement.close();
                        mConn.close();
                        return true;
                    }
                    results.close();
                    break;
                }


            } catch (Exception e) {
                try {
                    if (mStatement != null) {
                        mStatement.close();
                    }
                    if (mConn != null) {
                        mConn.close();
                    }

                    return false;
                } catch (SQLException ex) {
                    Logger.getLogger(DBHelper.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

            mStatement.close();
            mConn.close();
            return false;
        } catch (SQLException ex) {
            Logger.getLogger(DBHelper.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
    }

    public static ArrayList<String> getUsers() throws ClassNotFoundException, SQLException {
        ArrayList<String> retval = new ArrayList<String>();
        Connection mConn = null;
        Statement mStatement = null;

        Class.forName("com.mysql.jdbc.Driver");
        mConn = DriverManager.getConnection("jdbc:mysql://localhost/progin_4", "progin", "progin");
        mStatement = mConn.createStatement();

        String query = "SELECT * from `user` ";
        System.out.println("Query : " + query);
        ResultSet results = mStatement.executeQuery(query);
        while (results.next()) {
            retval.add(results.getString("username"));
        }
        results.close();
        mStatement.close();
        mConn.close();
        return retval;
    }
        
}
